// API 基础配置
// 开发环境使用代理，生产环境使用完整地址
const isDev = import.meta.env.DEV || process.env.NODE_ENV === 'development'
const API_BASE_URL = isDev ? '/api/student/' : 'http://60.205.2.196:8000/api/student/'
const API_BASE = isDev ? '/api/' : 'http://60.205.2.196:8000/api/'

console.log('=== API 配置 ===')
console.log('开发环境:', isDev)
console.log('API_BASE_URL:', API_BASE_URL)
console.log('API_BASE:', API_BASE)

function http({
  url,
  method = "post",
  data = {}
}) {
  return new Promise((resolve, reject) => {
    // 从本地存储获取 token
    let token = uni.getStorageSync('token') || '';
    
    // 确保 token 是字符串类型
    if (typeof token !== 'string') {
      // console.warn('⚠️ Token 类型错误，重置为空');
      token = '';
    }
    
    // 如果没有 token，尝试使用 userName 作为认证（临时方案）
    let userName = '';
    if (!token || token.length === 0) {
      userName = uni.getStorageSync('userName') || '';
    }
    
    console.log('=== HTTP 请求详情 ===');
    console.log('请求地址:', url);
    console.log('请求方法:', method);
    if (token) {
      console.log('携带token:', token.substring(0, 30) + '...');
    } else if (userName) {
      console.log('Session认证，用户:', userName);
    } else {
      console.log('⚠️ 无认证信息（可能是公开接口）');
    }
    
    // 构建请求头
    const header = {
      'Content-Type': 'application/json'
    };
    
    // 如果有 token，添加到 header
    if (token && token.length > 0) {
      header['token'] = token;
    }
    
    // 注释掉 userName 认证（后端不支持，会导致 500 错误）
    // if (userName && userName.length > 0) {
    //   header['userName'] = userName;
    // }
    
    uni.request({
      url: url,
      method: method,
      data: data,
      header: header,
      withCredentials: true,  // 允许携带 cookie（Session 认证）
      success: res => {
        console.log('=== HTTP 响应 ===');
        console.log('响应URL:', url);
        console.log('响应状态:', res.statusCode);
        console.log('响应code:', res.data?.code);
        console.log('响应message:', res.data?.message);
        
        // 如果返回 401，给出详细的提示
        if (res.data && res.data.code === 401) {
          console.error('❌ 401 未授权');
          console.error('可能原因：');
          console.error('1. 后端使用 Session 认证，但 CORS 配置不支持跨域凭证');
          console.error('2. 需要后端配置：');
          console.error('   - Access-Control-Allow-Credentials: true');
          console.error('   - Access-Control-Allow-Origin: http://localhost:5173 (不能是 *)');
          console.error('3. 或者需要使用代理服务器避免跨域');
          console.error('当前认证信息 - Token长度:', token.length, ', UserName:', userName);
        }
        
        resolve(res.data)
      },
      fail: err => {
        console.error('=== HTTP 错误 ===');
        console.error('错误URL:', url);
        console.error('错误信息:', JSON.stringify(err));
        reject(err)
      }
    })
  })
}

// API 接口集合 - 新接口文档地址: http://60.205.2.196:8000
export const api = {
  // ============ 用户认证相关 ============
  // 登录 (4.2.1) - 注意：这个接口不带 /student/
  login: (data) => {
    return http({ 
      url: `${API_BASE}user/login`, 
      method: 'post', 
      data: {
        userName: data.userName,
        password: data.password
      }
    });
  },
  
  // 注册 (4.2.2)
  register: (data) => http({ 
    url: `${API_BASE_URL}user/register`, 
    method: 'post', 
    data: { 
      userName: data.userName, 
      password: data.password, 
      confirmPassword: data.confirmPassword,
      userLevel: data.userLevel 
    }
  }),
  
  // 检查绑定 (4.2.3)
  checkBind: (code) => http({ 
    url: `${API_BASE_URL}user/register`, 
    method: 'post', 
    data: { code }
  }),
  
  // 解绑退出 (4.2.3)
  unbind: (token) => http({ 
    url: `${API_BASE_URL}auth/unBind`, 
    method: 'post', 
    data: { token }
  }),
  
  // ============ 用户信息相关 ============
  // 获取当前用户信息 (4.2.8)
  getCurrentUser: () => http({ 
    url: `${API_BASE_URL}user/current`, 
    method: 'post', 
    data: {}
  }),
  
  // 更新用户信息 (4.2.15)
  updateUserInfo: (data) => http({ 
    url: `${API_BASE_URL}user/update`, 
    method: 'post', 
    data: {
      id: data.id,
      userUuid: data.userUuid,
      userName: data.userName,
      realName: data.realName,
      age: data.age,
      role: data.role,
      sex: data.sex,
      birthDay: data.birthDay,
      phone: data.phone,
      lastActiveTime: data.lastActiveTime || '',
      createTime: data.createTime,
      modifyTime: data.modifyTime,
      status: data.status,
      userLevel: data.userLevel,
      classes: data.classes,
      imagePath: data.imagePath || ''
    }
  }),
  
  // 用户头像上传 (4.2.18) - 注意：接口路径为 user/picture
  updateAvatar: (file) => {
    const token = uni.getStorageSync('token') || '';
    return new Promise((resolve, reject) => {
      uni.uploadFile({
        url: `${API_BASE}user/picture`,
        filePath: file,
        name: 'file',
        header: {
          'token': token
        },
        success: res => {
          resolve(JSON.parse(res.data))
        },
        fail: err => {
          reject(err)
        }
      })
    })
  },
  
  // ============ 消息相关 ============
  // 消息列表 (4.2.16)
  getUserMessageList: (params) => http({ 
    url: `${API_BASE_URL}user/message/page`, 
    method: 'post', 
    data: { pageIndex: params.pageIndex, pageSize: params.pageSize }
  }),
  
  // 消息详情 (4.2.12)
  getMessageDetail: (messageId) => http({ 
    url: `${API_BASE_URL}user/message/read/${messageId}`, 
    method: 'post', 
    data: {}
  }),
  
  // 消息未读数 (4.1.13)
  getUnreadCount: () => http({ 
    url: `${API_BASE_URL}user/message/unreadCount`, 
    method: 'post', 
    data: {}
  }),
  
  // 标记消息已读 (4.1.14)
  markMessageRead: (messageId) => http({ 
    url: `${API_BASE_URL}user/message/read/${messageId}`, 
    method: 'post', 
    data: {}
  }),
  
  // 用户动态 (4.2.14)
  getUserLog: () => http({ 
    url: `${API_BASE_URL}user/log`, 
    method: 'post', 
    data: {}
  }),
  
  // ============ 主页相关 ============
  // 主页固定试卷、时段试卷 (4.2.3)
  getDashboardPaper: () => http({ 
    url: `${API_BASE_URL}dashboard/index`, 
    method: 'post', 
    data: {}
  }),
  
  // 任务中心 (4.2.4)
  getDashboardTask: () => http({ 
    url: `${API_BASE_URL}dashboard/task`, 
    method: 'post', 
    data: {}
  }),
  
  // ============ 试卷相关 ============
  // 学科列表 (4.2.4)
  getSubjectList: () => http({ 
    url: `${API_BASE_URL}education/subject/list`, 
    method: 'post', 
    data: {}
  }),
  
  // 试卷列表 (4.2.5)
  getPaperList: (params) => {
    console.log('getPaperList 接收到的参数:', params);
    const data = { 
      paperType: params.paperType, 
      pageIndex: params.pageIndex, 
      pageSize: params.pageSize
    };
    if (params.subjectId) {
      data.subjectId = params.subjectId;
    }
    console.log('准备发送的数据:', data);
    return http({ 
      url: `${API_BASE_URL}exam/paper/pageList`, 
      method: 'post', 
      data: data
    });
  },
  
  // 试卷答题 (4.2.10)
  selectPaper: (paperId) => {
    console.log('selectPaper 被调用，paperId:', paperId);
    return http({ 
      url: `${API_BASE_URL}exam/paper/select/${paperId}`, 
      method: 'post', 
      data: {}
    }).then(res => {
      console.log('========== selectPaper API 返回数据开始 ==========');
      console.log('状态码 code:', res?.code);
      console.log('消息 message:', res?.message);
      
      if (res?.response?.titleItems?.[0]?.questionItems?.[0]) {
        const firstQuestion = res.response.titleItems[0].questionItems[0];
        console.log('第一个题目的完整数据:');
        console.log(JSON.stringify(firstQuestion, null, 2));
      }
      
      console.log('========== selectPaper API 返回数据结束 ==========');
      return res;
    });
  },
  
  // ============ 答卷相关 ============
  // 考试记录列表 (4.2.7)
  getExamRecordList: (params) => {
    console.log('getExamRecordList 接收到的参数:', params);
    return http({ 
      url: `${API_BASE_URL}exampaper/answer/pageList`,
      method: 'post', 
      data: { 
        pageIndex: params.pageIndex, 
        pageSize: params.pageSize 
      }
    });
  },
  
  // 查看试卷 (4.2.10)
  getExamPaperDetail: (paperId) => http({ 
    url: `${API_BASE_URL}exampaper/answer/read/${paperId}`, 
    method: 'post', 
    data: {}
  }),
  
  // 提交试卷 (4.2.11)
  submitExamAnswer: (data) => {
    console.log('submitExamAnswer 接收到的参数:', JSON.stringify(data));
    return http({ 
      url: `${API_BASE_URL}exampaper/answer/answerSubmit`, 
      method: 'post', 
      data: data
    });
  },
  
  // 批改试卷 (4.2.13)
  judgeExamPaper: (data) => {
    console.log('judgeExamPaper 接收到的参数:', JSON.stringify(data));
    return http({ 
      url: `${API_BASE_URL}exampaper/answer/edit`, 
      method: 'post', 
      data: data
    });
  },
  
  // ============ 视频相关 (暂未使用) ============
  getVideoList: (params) => http({ 
    url: `${API_BASE_URL}video/pageList`, 
    method: 'post', 
    data: params
  }),
  
  selectVideo: (videoId) => http({ 
    url: `${API_BASE_URL}video/select/${videoId}`, 
    method: 'post', 
    data: {}
  }),
  
  // ============ 错题本相关 ============
  // 错题本列表 (4.2.9)
  getWrongQuestions: (params) => http({ 
    url: `${API_BASE_URL}question/answer/page`, 
    method: 'post', 
    data: { 
      pageIndex: params.pageIndex, 
      pageSize: params.pageSize 
    }
  }),
  
  // 错题本详情 (4.2.9)
  getWrongQuestionDetail: (id) => http({ 
    url: `${API_BASE_URL}question/answer/select/${id}`, 
    method: 'post', 
    data: {}
  }),
  
  // ============ 班级相关 ============
  // 加入班级 (4.2.17) - 注意：接口路径为 classes/join
  joinClass: (data) => http({ 
    url: `${API_BASE}classes/join`, 
    method: 'post', 
    data
  }),
}

export default http